package com.txby.dplus.common.controller;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.txby.dplus.common.annomapper.MybatisBaseDaoCRUD;
import com.txby.dplus.common.data.CommonApiModelMapExt;
import com.txby.dplus.common.data.ConstantErrCode;
import com.txby.dplus.common.utils.IPUtils;
import com.txby.dplus.common.utils.RedisUtils;
import com.txby.dplus.common.utils.util.ChkUtil;
import com.txby.dplus.common.utils.util.HttpToolUtil;
import com.txby.dplus.common.utils.util.Times;

@SuppressWarnings("all")
public class CommonController {
    @Autowired
    public MybatisBaseDaoCRUD mBaseDao;
    @Autowired
    private RedisUtils redisUtils;
    
    public  ThreadLocal<Boolean> isTokenValid= new ThreadLocal();// 是否token有效
    public  ThreadLocal<CommonApiModelMapExt>  mm =new ThreadLocal() ;
    public  ThreadLocal<String>  apiUserId =new ThreadLocal() ;// 用户id
    public  ThreadLocal<String>  userToken =new ThreadLocal() ;// 当前token
    public  ThreadLocal<HttpServletRequest>  request =new ThreadLocal() ; 
    public  ThreadLocal<HttpServletResponse>  response =new ThreadLocal() ; 
    
    public  ThreadLocal<String>  userAgent =new ThreadLocal() ; 
    public  ThreadLocal<String>  requestMethod =new ThreadLocal() ; 
    public  ThreadLocal<String>  clientIP =new ThreadLocal() ; 
    
    
    public Map reParamTypeMap = new HashMap() {{// 当前请求类型  0:web,1:android,2:iphone3:微信wechat
        put(0, "web");
        put(1, "android");
        put(2, "iphone");
        put(3, "wechat");
    }};// 当前请求类型Map  0:web,1:android,2:iphone3:微信
    
   

    private static Logger logger = LoggerFactory.getLogger(CommonController.class);

    /**
     * 上传单文件（文件name参数名file）,按日期hh:mmss:sss命名 code 4017: 上传出现异常 4018:
     * 上传文件大小受限制（不能超过2M） 4019:文件格式受限制（支持gif、png、jpg、bmp）
     *
     * @param request
     * @param savePath
     * @return
     */

    public Map fileUpload(HttpServletRequest request, String savePath) {
        Map m = new HashMap();
        m.put(CommonApiModelMapExt.ERRCODE, 4017);
        m.put(CommonApiModelMapExt.CODE, 4017);
        m.put(CommonApiModelMapExt.ERRMSG, "上传出现异常");
        m.put(CommonApiModelMapExt.MSG, "上传出现异常");
        m.put(CommonApiModelMapExt.INFO, "上传出现异常");
        m.put("url", "");
        try {
            Date date = new Date();
            String newName = Times.getDateToStringHHmmssSSS(date);// 自定义文件名字
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
            CommonsMultipartFile orginalFile = (CommonsMultipartFile) multipartRequest
                    .getFile("tradingCertificatePicFile");// 表单中对应的文件名；
            if (orginalFile != null && !orginalFile.isEmpty()) {
                String fileName = orginalFile.getOriginalFilename();
                String suffix = fileName.substring(fileName.indexOf("."));// 获得后缀名

                long size = orginalFile.getSize();
                /*
                 * if(orginalFile.getSize()>6024*2000){ m.put("code", "4018");
                 * m.put("info","图片上传文件大小受限制（不能超过2M）"); m.put("msg",
                 * "图片不能大于2M"); return m; }
                 */

                if (!suffix.equals(".bmp") && !suffix.equals(".gif") && !suffix.equals(".png")
                        && !suffix.equals(".jpg")) {
                    m.put("code", "4019");
                    m.put("info", "文件格式受限制（支持gif、png、jpg、bmp）");
                    m.put("msg", "上传格式应为gif、png、jpg、bmp");
                    m.put(CommonApiModelMapExt.ERRCODE, 4019);
                    m.put(CommonApiModelMapExt.CODE, 4019);
                    m.put(CommonApiModelMapExt.ERRMSG, "文件格式受限制（支持gif、png、jpg、bmp）");
                    m.put(CommonApiModelMapExt.MSG, "文件格式受限制（支持gif、png、jpg、bmp）");
                    m.put(CommonApiModelMapExt.INFO, "文件格式受限制（支持gif、png、jpg、bmp）");
                    return m;
                }
                fileName = newName + suffix;
                File file = new File(savePath);
                if (!file.exists()) {// 判断文件夹是否存在，不存在就根据上面的路径创建文件夹
                    file.mkdirs();
                }
                String realpath = request.getSession().getServletContext().getRealPath(savePath);// 给予存储路径
                File f = new File(realpath + File.separator + fileName);
                String url = savePath + fileName;// 获得相对路径
                FileUtils.copyInputStreamToFile(orginalFile.getInputStream(), f);// 获取文件，并按照路径保存

                m.put(CommonApiModelMapExt.ERRCODE, 0);
                m.put(CommonApiModelMapExt.CODE, 1);
                m.put(CommonApiModelMapExt.ERRMSG, "上传成功");
                m.put(CommonApiModelMapExt.MSG, "上传成功");
                m.put(CommonApiModelMapExt.INFO, "上传成功");
                m.put("url", url);
                m.put("date", date);
                return m;
            }

        } catch (Exception e) {
            e.printStackTrace();

            return m;
        }

        return m;
    }




    /**
     * @param sqlId
     * @return
     * @Description:sql in条件查询拆分
     */
    public static String getSplitInSql(String[] sqlId) {
        String sql = "";
        for (String str : sqlId) {
            sql += "'" + str + "',";
        }
        if (!ChkUtil.isEmpty(sql)) {
            sql = sql.substring(0, sql.length() - 1);
        }
        return sql;
    }

    /**
     * @param sqlId
     * @return
     * @Description: sql in条件查询拆分
     */
    public static String getSplitInSql(Set<String> sqlId) {
        String sql = "";
        for (String str : sqlId) {
            sql += "'" + str + "',";
        }
        if (!ChkUtil.isEmpty(sql)) {
            sql = sql.substring(0, sql.length() - 1);
        }
        return sql;
    }

    /**
     * @param sqlId
     * @return
     * @Description: 保存数据表中，外键id的“，”分割的拆分
     */
    public static String getSplitNewString(String[] sqlId) {
        String sql = "";
        for (String str : sqlId) {
            sql += str + ",";
        }
        if (!ChkUtil.isEmpty(sql)) {
            sql = sql.substring(0, sql.length() - 1);
        }
        return sql;
    }

    /**
     * @param sqlId
     * @return
     * @Description: 保存数据表中，外键id的“，”分割的拆分
     */
    public static String getSplitNewString(Set<String> sqlId) {
        String sql = "";
        for (String str : sqlId) {
            sql += str + ",";
        }
        if (!ChkUtil.isEmpty(sql)) {
            sql = sql.substring(0, sql.length() - 1);
        }
        return sql;
    }



    @ModelAttribute
    public void initUserRequest(HttpServletRequest request,HttpServletResponse response) throws IOException {
//		 reParamTypeMap=new HashMap() ;// 当前请求类型  0:web,1:android,2:iphone3:微信wechat
//		 put(0, "web");
//		 put(1, "android");
//		 put(2, "iphone");
//		 put(3, "wechat");
    	mm.set(new CommonApiModelMapExt(ConstantErrCode.CODE_0.getCode(), ConstantErrCode.CODE_0.getInfo()));
    	userAgent.set( request.getHeader("user-agent"));
    	this.request.set(request);
        this.response.set(response);
        this.requestMethod.set(request.getMethod().toUpperCase());
        try {
            this.clientIP.set( IPUtils.getIpAddr(request));
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    /**
     * http请求返回json
     *
     * @param httpUrl
     * @param httpType
     * @param maps
     * @return
     * @throws IOException
     */
    public String getHttpResponseContent(String httpUrl, String httpType, Map<String, String> maps) throws IOException {
        String responseContent = HttpToolUtil.getInstance().sendHttpCustom(httpUrl, httpType, maps, false, null);
        return responseContent;
    }


    /**
     * 反转List 集合数据
     *
     * @param @param  fullRegion
     * @param @return 设定文件
     * @return String    返回类型
     * @throws
     * @Title: getDeviceHosInfoByRegionListReveseString
     * @Description: TODO(这里用一句话描述这个方法的作用)
     */
    public static String getDeviceHosInfoByRegionListReveseString(List<String> fullRegion) {
        String regionName = "";
        int size = fullRegion != null ? fullRegion.size() : 0;
        for (int i = size - 1; i >= 0; i--) {
            if (i != 0) {
                regionName += fullRegion.get(i) + "-";
            } else {
                regionName += fullRegion.get(i);
            }
        }
        return regionName;
    }

    /**
     * 处理like查询条件的通配及sql注入
     *
     * @param @param  containStr
     * @param @param  fieldName
     * @param @return 设定文件
     * @return Map    返回类型
     * @throws
     * @Title: getLikeSTransferSql
     * @Description: TODO(这里用一句话描述这个方法的作用)
     */
    public static Map getLikeSTransferSql(String containStr, String fieldName) {
        String sql = "";
        String fieldValue = "";
        if (!ChkUtil.isEmptyAllObject(containStr)) {
            String paramFieldName = fieldName.contains(".") ? fieldName.substring(fieldName.lastIndexOf(".") + 1, fieldName.length()) : fieldName;
            if (containStr.contains("%") || containStr.contains("_")) {
                containStr = containStr.trim().replace("%", "\\%").replace("_", "\\_");
                containStr = "%" + containStr + "%";
                sql += " and " + fieldName + " like #{pojo." + paramFieldName + "} escape '\\'  ";
            } else {
                containStr = "%" + containStr + "%";
                sql += " and " + fieldName + " like #{pojo." + paramFieldName + "} ";
            }
            fieldName = paramFieldName;
        } else {

            return null;
        }

        Map data = new HashMap();
        data.put("fieldName", fieldName);
        data.put("fieldValue", containStr);
        data.put("sql", sql);
        return data;
    }

	/**
	 * 
	 * 	Map m=new HashMap();
		m.put("ip", ip);
		m.put("port", port);
		m.put("dbname", dbname);
		return m;
	* @Title: getJdbcInfoByJdbcUrl 
	* @Description: TODO(这里用一句话描述这个方法的作用) 
	* @param @param jdbcurl
	* @param @return    设定文件 
	* @return Map    返回类型 
	* @throws
	 */
	public static Map<String,String> getJdbcInfoByJdbcUrl(String jdbcurl){
		String ip="";
		String port="";
		String dbname="";
		Map m=new HashMap();
		if(ChkUtil.isEmpty(jdbcurl)) {
			m.put("ip", ip);
			m.put("port", port);
			m.put("dbname", dbname);
			return m;
		}
		jdbcurl=jdbcurl.toLowerCase().trim();
		if(jdbcurl.startsWith("jdbc:sqlserver")){
			if(jdbcurl.indexOf("//")!=-1&&jdbcurl.indexOf(";")!=-1&&jdbcurl.lastIndexOf("=")!=-1) {
				if((jdbcurl.indexOf("//")+2<jdbcurl.indexOf(";"))) {
					String ipprot=jdbcurl.substring(jdbcurl.indexOf("//")+2,jdbcurl.indexOf(";"));
					String[] ipprotArrays =ipprot.split(":");
					if(ipprotArrays.length>1) {
						ip=ipprotArrays[0];
						port=ipprotArrays[1];
					}
				}
				if(jdbcurl.lastIndexOf("=")+1<jdbcurl.length()) {
					dbname=jdbcurl.substring(jdbcurl.lastIndexOf("=")+1);
				}
			}
		}else if(jdbcurl.startsWith("jdbc:mysql")){
			if(jdbcurl.indexOf("//")!=-1&&jdbcurl.lastIndexOf("/")!=-1) {
				if(jdbcurl.indexOf("//")+2<jdbcurl.lastIndexOf("/")) {
					String ipprot=jdbcurl.substring(jdbcurl.indexOf("//")+2,jdbcurl.lastIndexOf("/"));
					String[] ipprotArrays =ipprot.split(":");
					if(ipprotArrays.length>1) {
						ip=ipprotArrays[0];
						port=ipprotArrays[1];
					}
				}
			}
			
			if(jdbcurl.lastIndexOf("/")+1<(jdbcurl.lastIndexOf("?")!=-1?jdbcurl.lastIndexOf("?"):jdbcurl.length())) {
				dbname=jdbcurl.substring(jdbcurl.lastIndexOf("/")+1,jdbcurl.lastIndexOf("?")!=-1?jdbcurl.lastIndexOf("?"):jdbcurl.length());
			}
			
		} else if(jdbcurl.startsWith("jdbc:oracle:thin")){
			if(jdbcurl.indexOf("@")+1!=-1&&jdbcurl.lastIndexOf(":")!=-1) {
				if(jdbcurl.indexOf("@")+1<jdbcurl.lastIndexOf(":")) {
					String ipprot=jdbcurl.substring(jdbcurl.indexOf("@")+1,jdbcurl.lastIndexOf(":"));
					String[] ipprotArrays =ipprot.split(":");
					if(ipprotArrays.length>1) {
						ip=ipprotArrays[0];
						port=ipprotArrays[1];
					}
				}
			}
			if(jdbcurl.lastIndexOf(":")+1<jdbcurl.length()) {
				dbname=jdbcurl.substring(jdbcurl.lastIndexOf("/")+1,jdbcurl.lastIndexOf("?")!=-1?jdbcurl.lastIndexOf("?"):jdbcurl.length());
				dbname=jdbcurl.substring(jdbcurl.lastIndexOf(":")+1);
			}
	    }
	
		m.put("ip", ip);
		m.put("port", port);
		m.put("dbname", dbname);
		return m;
	}
 
	public static String  getJdbcDriverClassNameByJdbcUrl(String jdbcurl){
		jdbcurl=jdbcurl.toLowerCase().trim();
		String driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver";
		if(jdbcurl.startsWith("jdbc:sqlserver")){
			driverClassName="com.microsoft.sqlserver.jdbc.SQLServerDriver";
		}else if(jdbcurl.startsWith("jdbc:mysql")){
			 driverClassName="com.mysql.jdbc.Driver";
		} else if(jdbcurl.startsWith("jdbc:oracle:thin")){
			  driverClassName="oracle.jdbc.driver.OracleDriver";
		}else {
			 driverClassName="org.postgresql.Driver";
		}
		return driverClassName;
	}
	

}
